using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using RealDolmen.SharePoint.Helpers;

namespace RealDolmen.SharePoint.ListFeatures
{
    public class ListFeatureActivator : UserControl
    {
        #region Fields
        protected Label lblEmpty;
        protected Repeater repeater;
        private DataTable dataTable;
        #endregion // Fields

        #region Events
        protected void BtnActivateFeature_Click(object objSender, EventArgs evtargs)
        {
            Button button = (Button)objSender;
            Guid featureGuid = new Guid(button.CommandArgument);

            ListFeature feature = ListFeature.Instantiate(featureGuid, SPContext.Current.List, SPContext.Current.Web);

            if (feature.IsActive)
                feature.Deactivate();
            else
                feature.Activate();

            SPUtility.Redirect(
                string.Format("{0}{1}",
                    SPContext.Current.Web.Url,
                    HttpContext.Current.Request.Url.PathAndQuery),
                SPRedirectFlags.Default, HttpContext.Current);
        }

        protected void BtnSettings_Click(object objSender, EventArgs evtargs)
        {
            Button button = (Button)objSender;
            Guid featureGuid = new Guid(button.CommandArgument);

            ListFeature feature = ListFeature.Instantiate(featureGuid, SPContext.Current.List, SPContext.Current.Web);

            SPUtility.Redirect(feature.SettingsUrlRelative, SPRedirectFlags.Static, HttpContext.Current);
        }

        protected void BtnAdd_Click(object objSender, EventArgs evtargs)
        {
            SPUtility.Redirect(AddFeatureUrl, SPRedirectFlags.Static, HttpContext.Current);
        }

        protected override void OnLoad(EventArgs evtargs)
        {
            base.OnLoad(evtargs);
            EnsureChildControls();

            string action = string.Empty;


            if (Request.QueryString["Action"] != null)
                action = Request.QueryString["Action"];
            else if (Request.QueryString["action"] != null)
                action = Request.QueryString["action"];

            if (!string.IsNullOrEmpty(action))
            {
                action = action.Trim().ToLower();
                if (action == "clean" || action == "clear")
                {
                    ListFeature.DeleteProperties(new ListFeatureKeyManager(SPContext.Current.List), SPContext.Current.Web);
                }
                else if (action == "cleanweb" || action == "clearweb")
                {
                    ListFeature.DeleteProperties(new ListFeatureKeyManager(), SPContext.Current.Web);
                }
            }

            this.repeater.DataSource = this.DataTable;
            this.repeater.DataBind();
            if (this.DataTable.Rows.Count == 0)
            {
                this.lblEmpty.Text = SPHttpUtility.HtmlEncode(SPResource.GetString("NoFeaturesText", new object[0]));
            }
        }

        #endregion // Events

        #region Properties
        protected string AddFeatureUrl
        {
            get
            {
                return string.Format("{1}/_layouts/AddListFeature.aspx?List={0}",
                    SPContext.Current.ListId,
                    SPContext.Current.Web.Url);
            }
        }

        private DataTable DataTable
        {
            get
            {
                if (this.dataTable == null)
                {
                    this.dataTable = this.BuildFeatureListDataTable();
                }
                return this.dataTable;
            }
        } 
        #endregion // Properties

        #region DataTable Contruction
        private void AddFeaturesToTable(ref DataTable dtblFeatureList)
        {
            List<ListFeature> listFeatures =
                ListFeature.GetListFeatures(SPContext.Current.List);

            foreach (ListFeature listFeature in listFeatures)
            {
                DataRow row = BuildDataRowFromListFeature(listFeature, dtblFeatureList);
                dtblFeatureList.Rows.Add(row);
            }
        }

        private DataRow BuildDataRowFromListFeature(ListFeature feature, DataTable dtblFeatures)
        {
            CultureInfo languageCulture = SPHelper.CurrentCultureInfo;
            DataRow row = dtblFeatures.NewRow();

            row["FeatureId"] = feature.Id.ToString();
            row["Title"] = feature.GetTitle(languageCulture);
            row["ImageUrl"] = feature.Definition.GetImageUrl(languageCulture);
            row["ImageAlt"] = feature.Definition.GetImageAltText(languageCulture);
            row["SettingsUrl"] = feature.SettingsUrlRelative;
            row["ClassName"] = "inactiveText";
            row["Description"] = feature.Definition.GetDescription(languageCulture);

            if (feature.Definition.Exists)
            {
                row["Error"] = false;
                row["ErrorDescription"] = string.Empty;
                if (!feature.IsActive)
                {
                    row["Active"] = false;
                    row["Inactive"] = true;
                }
                else
                {
                    row["Active"] = true;
                    row["Inactive"] = false;
                    row["ClassName"] = "";
                }
            }
            else
            {
                row["Error"] = true;
                row["ErrorDescription"] = HttpContext.GetGlobalResourceObject("lf", "ListFeaturesErrorNotInstalledNotActive");
                row["Inactive"] = false;
                row["Active"] = false;
            }

            return row;
        }

        private DataTable BuildFeatureListDataTable()
        {
            string[] strArray = new string[] { "FeatureId", "ImageUrl", "ImageAlt", "Title", "Description", "Active", "Inactive", "Error", "ErrorDescription", "ClassName", "SettingsUrl" };
            DataTable dtblFeatureList = new DataTable();

            foreach (string col in strArray)
            {
                dtblFeatureList.Columns.Add(
                    new DataColumn(col, typeof(string)));
            }

            this.AddFeaturesToTable(ref dtblFeatureList);

            dtblFeatureList.Locale = CultureInfo.CurrentUICulture;
            dtblFeatureList.DefaultView.Sort = "Title ASC";
            return dtblFeatureList;
        }

        #endregion // DataTable Contruction
    }
}
